import React, { useState, useEffect } from 'react';
import { Button, CircularProgress } from '@mui/material';
import { PersonAdd as PersonAddIcon, PersonRemove as PersonRemoveIcon } from '@mui/icons-material';
import { useFriends } from '../FriendsContext';

interface FriendActionButtonProps {
  userId: number;
  onActionComplete?: () => void;
}

const FriendActionButton: React.FC<FriendActionButtonProps> = ({ userId, onActionComplete }) => {
  const { addFriend, removeFriend, checkFriendship, loading } = useFriends();
  const [isFriend, setIsFriend] = useState<boolean>(false);
  const [checking, setChecking] = useState<boolean>(true);

  useEffect(() => {
    const checkStatus = async () => {
      try {
        setChecking(true);
        const status = await checkFriendship(userId);
        setIsFriend(status);
      } catch (error) {
        console.error('检查好友状态失败:', error);
      } finally {
        setChecking(false);
      }
    };

    checkStatus();
  }, [userId, checkFriendship]);

  const handleAction = async () => {
    try {
      if (isFriend) {
        await removeFriend(userId);
        setIsFriend(false);
      } else {
        await addFriend(userId);
        setIsFriend(true);
      }
      onActionComplete?.();
    } catch (error) {
      console.error('好友操作失败:', error);
    }
  };

  if (checking) {
    return <CircularProgress size={24} />;
  }

  return (
    <Button
      variant="contained"
      color={isFriend ? 'error' : 'primary'}
      startIcon={isFriend ? <PersonRemoveIcon /> : <PersonAddIcon />}
      onClick={handleAction}
      disabled={loading}
    >
      {isFriend ? '删除好友' : '添加好友'}
    </Button>
  );
};

export default FriendActionButton;